<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { ElMessage, ElNotification } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useScenicMapManageStore } from '@/stores/useScenicMapStore'
import { useMapManageStore } from '@/stores/useMapContainerStore.ts'
import variable from '@/utils/properties.yaml'
import { VTooltip } from 'v-tooltip'
import ScenicCard from '@/components/scenics/ScenicCard.vue'

let map = null

// const searchContent = ref('123')
// function searchContentByKeys() {
//   AMap.plugin(['AMap.PlaceSearch'], function () {
//     const placeSearch = new AMap.PlaceSearch({
//       pageSize: 5, //单页显示结果条数
//       pageIndex: 1, //页码
//       city: '010', //兴趣点城市
//       citylimit: false, //是否强制限制在设置的城市内搜索
//       map: map, //展现结果的地图实例
//       panel: 'place-panel',
//       autoFitView: true,
//     })
//     AMap.event.addListener(placeSearch, "complete", keywordSearch_CallBack); //返回结果
//     placeSearch.search(searchContent.value) //使用插件搜索关键字并查看结果
//   })
// }
window._AMapSecurityConfig = {
  securityJsCode: variable.process.securityJsCode,
}
const scenicMapManage = useScenicMapManageStore()
const scenics = computed(() => scenicMapManage.briefScenicArray)
const showCard = computed(() => scenicMapManage.showCard)
onMounted(async () => {
  console.log('挂载完毕')
  await scenicMapManage.getAllScenicInfor()
  AMapLoader.load({
    key: variable.process.AMap_KEY,
    version: '2.0',
    plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.MapType'], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((AMap) => {
      //新建图层
      const layer = new AMap.createDefaultLayer({
        zooms: [3, 20],
        visible: true,
        opacity: 1,
        zIndex: 0,
      })
      //创建地图
      map = new AMap.Map('container', {
        // 设置地图容器id
        // //3D模式需要设置的
        // pitch:50,
        // rotateEnable:true,
        // pitchEnable:true,
        // rotation:-15,
        // zooms:[2,20],
        // terrain:true,
        // viewMode: '3D', // 是否为3D地图模式
        viewMode: '2D',
        mapStyle: 'amap://styles/normal', //地图样式
        zoom: 14.5, // 初始化地图级别
        layer: [layer],
        center: [106.55, 29.57], // 初始化地图中心点位置
      })
      ElNotification({
        message: '地图成功加载！',
        type: 'success',
      })
      if (scenics.value != null) {
        //展示景点信息
        const markerContent = `<div class="custom-content-marker">
      <img src="src/assets/scenicNote.png"></div>`

        scenics.value.forEach((scenic) => {
          const position = new AMap.LngLat(scenic.longitude, scenic.latitude)
          const marker = new AMap.Marker({
            position: position,
            icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
            title: scenic.scenicName,
            visible: true,
            cursor: 'pointer',
            label: '文本标注',
            content: markerContent,
            offset: new AMap.Pixel(-13, -30),
          })

          const infoWindow = new AMap.InfoWindow({
            isCustom: true,
            content: `
              <div class="scenic-infowindow" style="background-color: white;width: 200px;border-radius: 10px;">
                <img class="infowindow-img" src="${scenic.scenicPics?.[0] || 'https://cdn.jsdelivr.net/gh/xiaoliao111/sta-images@main/scenery/30c7cb19-7771-4e1e-9599-444510e2499e.jpg'}" alt="图片" width="100%"/>
                <div class="infowindow-content">
                  <div class="infowindow-title">
                    ${scenic.scenicName}
                  </div>
                  <div class="infowindow-meta">
                    <span>评分：${scenic.rating}⭐</span>
                    <span>热度：${scenic.popularity}</span>
                  </div>
                  <div class="infowindow-price">￥${scenic.price} 起</div>
                </div>
              </div>
            `,
            // autoMove: true,
            closeWhenClickMap: true,
            offset: new AMap.Pixel(0, -40),
          })

          marker.on('mouseover', () => {
            //窗体信息
            const pixel = map.lngLatToContainer(marker.getPosition())
            const mapSize = map.getSize()

            // 判断在地图哪个象限
            let offsetX = 0
            const offsetY = -40
            if (pixel.getX() > mapSize.width * 0.75) {
              offsetX = -260 // marker 靠右，让窗体向左偏移
            }

            infoWindow.setOffset(new AMap.Pixel(offsetX, offsetY))
            infoWindow.open(map, marker.getPosition())
          })
          marker.on('mouseout', () => {
            infoWindow.close()
          })
          marker.on('click', () => {
            console.log('点击了景点信息')
            scenicMapManage.getScenicDetail(scenic.scenicId)
          })
          console.log(`该景点是${scenic.scenicName}`)
          console.log('添加标记点')
          map.add(marker)

          map.on('click', () => {
            scenicMapManage.closeCard()
            console.log('点击了地图某一侧')
          })
        })
      } else {
        ElMessage.info('暂无景点信息')
      }
      /**
       * 添加图层--路况图
       */
      // const traffic = new AMap.TileLayer.Traffic({
      //   autoRefresh: true,
      //   interval: 180, //刷新路况
      // })
      // map.add(traffic) //添加到图层中
      /**
       * 放大缩小--插件
       */
      //异步加载缩放插件
      AMap.plugin('AMap.ToolBar', function () {
        const toolbar = new AMap.ToolBar({
          position: {
            bottom: '50px',
            left: '10px',
          },
        })
        map.addControl(toolbar)
      })
      // //添加比例尺
      // AMap.plugin('AMap.Scale', function () {
      //   const scale = new AMap.Scale({
      //     position:{
      //       bottom:'10px',
      //       left:'10px',
      //     }
      //   })
      //   map.addControl(scale)
      // })
      //添加图层类型
      map.plugin(['AMap.MapType'], function () {
        const type = new AMap.MapType({
          defaultType: 0,
          position: {
            top: '100px',
            left: '10px',
          },
        })
        map.addControl(type)
      })
      // //地图的定位
      // map.plugin('AMap.Geolocation', function () {
      //   const geolocation = new AMap.Geolocation({
      //     enableHighAccuracy: true, //是否使用高精度定位，默认:true
      //     timeout: 10000, //超过10秒后停止定位，默认：无穷大
      //     buttonPosition: 'LB', //定位按钮的停靠位置
      //     buttonOffset: new AMap.Pixel(10, 100), //定位按钮与设置的停靠位置的偏移量
      //     zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
      //     // showMarker: true, //是否显示定位点
      //     // showCircle: true, //是否显示定位精度圈
      //   })
      //   map.addControl(geolocation)
      //   geolocation.getCurrentPosition()
      //   // AMap.event.addListener(geolocation, 'complete', (data) => {
      //   //   ElMessage({
      //   //     message: '定位成功',
      //   //     type: 'success',
      //   //   })
      //   // }) //返回定位信息
      // })
      //根据用户输入的关键字查询地点

      /**
       * 添加点标记--新类
       */
      // const markerContent = `<div class="custom-content-marker">
      //           <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png">
      //           <div class="close-btn" onclick="clearMarker()">X</div>
      //           </div>`
      // const position = new AMap.LngLat(116.397428, 39.90923)
      // const marker = new AMap.Marker({
      //   position: position,
      //   content: markerContent,
      //   offset: new AMap.Pixel(-13, -30),
      // })
      // map.add(marker)
      // function clearMarker() {
      //   map.remove(marker)
      // }
      // document.querySelector('.close-btn').onclick = clearMarker
      /**
       * 添加多边形---新类
       */
      // const pathArr = [
      //   [
      //     [
      //       [121.7789, 31.3102],
      //       [121.7279, 31.3548],
      //       [121.5723, 31.4361],
      //       [121.5093, 31.4898],
      //       [121.5624, 31.4864],
      //       [121.5856, 31.4547],
      //       [121.7694, 31.3907],
      //       [121.796, 31.3456],
      //       [121.7789, 31.3102],
      //     ],
      //   ],
      // ]
      // const polygon = new AMap.Polygon({
      //   path: pathArr, //多边形路径
      //   fillColor: '#ccebc5', //多边形填充颜色
      //   strokeOpacity: 1, //线条透明度
      //   fillOpacity: 0.5, //填充透明度
      //   strokeColor: '#2b8cbe', //线条颜色
      //   strokeWeight: 1, //线条宽度
      //   strokeStyle: 'dashed', //线样式
      //   strokeDasharray: [5, 5], //轮廓的虚线和间隙的样式
      // })
      // //鼠标移入更改样式
      // polygon.on('mouseover', () => {
      //   polygon.setOptions({
      //     fillOpacity: 0.7, //多边形填充透明度
      //     fillColor: '#7bccc4',
      //   })
      // })
      // //鼠标移出恢复样式
      // polygon.on('mouseout', () => {
      //   polygon.setOptions({
      //     fillOpacity: 0.5,
      //     fillColor: '#ccebc5',
      //   })
      // })
      // map.add(polygon)

      /**
       * 路线规划--插件
       */
      // const points = [
      //   { keyword: '北京市地震局（公交站）', city: '北京' },
      //   { keyword: '亦庄文化园（地铁站）', city: '北京' },
      // ]
      // //引入和创建驾车规划插件
      // AMap.plugin(['AMap.Driving'], function () {
      //   const driving = new AMap.Driving({
      //     map: map,
      //     panel: 'car-panel', //参数值为你页面定义容器的 id 值<div id="my-panel"></div>
      //   })
      //   //获取起终点规划线路
      //   driving.search(points, function (status:string, result:any) {
      //     if (status === 'complete') {
      //       //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
      //       //查询成功时，result 即为对应的驾车导航信息
      //       console.log(result)
      //     } else {
      //       console.log('获取驾车数据失败：' + result)
      //     }
      //   })
      // })
    })
    .catch((e) => {
      ElNotification({
        message: '地图加载过程中出问题：' + e.message,
        type: 'error',
      })
    })
})
onUnmounted(() => {
  console.log('销毁地图')
  map?.destroy()
})
</script>

<template>
  <div id="map-container">
    <div id="container"></div>
    <div id="scenic-detail-right" v-if="showCard">
      <scenic-card></scenic-card>
    </div>
  </div>
  <!--  <el-row>-->
  <!--    <el-col :xs="24" :sm="23" :md="24" :lg="24" :xl="24">-->
  <!--      <div id="container"></div>-->
  <!--      -->
  <!--    </el-col>-->
  <!--    &lt;!&ndash;    <el-col :xs="24" :sm="6" :md="12" :lg="6" :xl="6">&ndash;&gt;-->
  <!--    &lt;!&ndash;      &lt;!&ndash; <div class="operation">&ndash;&gt;-->
  <!--    &lt;!&ndash;        <el-input v-model="searchContent" style="width: 100px" size="large" placeholder="Please input"&ndash;&gt;-->
  <!--    &lt;!&ndash;          :suffix-icon="Search" @change="searchContentByKeys()">&ndash;&gt;-->
  <!--    &lt;!&ndash;        </el-input>&ndash;&gt;-->
  <!--    &lt;!&ndash;        <div id="place-panel"></div>&ndash;&gt;-->
  <!--    &lt;!&ndash;      </div> &ndash;&gt;&ndash;&gt;-->
  <!--    &lt;!&ndash;    </el-col>&ndash;&gt;-->
  <!--  </el-row>-->
</template>

<style scoped>
#map-container {
  width: 100%;
  position: relative;
}

.el-row {
  margin: 0;
  padding: 0;
  width: 100%;
}

#container {
  width: 100%;
  height: 600px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.el-row .el-col .operation {
  display: flex;
  flex-flow: column;
}

#scenic-detail-right {
  width: 300px;
  height: 550px;
  position: absolute;
  right: 10px;
  top: 20px;
  overflow-y: auto;
}

/*
*点标记的效果
*/
.custom-content-marker {
  position: relative;
  width: 10px;
  height: 20px;
}

.custom-content-marker:hover .custom-content-card {
  display: block;
}

.custom-content-marker img {
  width: 50%;
  height: 50%;
}

.custom-content-marker .close-btn {
  position: absolute;
  top: -6px;
  right: -8px;
  width: 15px;
  height: 15px;
  font-size: 12px;
  background: #ccc;
  border-radius: 50%;
  color: #fff;
  text-align: center;
  line-height: 15px;
  box-shadow: -1px 1px 1px rgba(10, 10, 10, 0.2);
}

.scenic-infowindow {
  display: flex;
  //width: 260px;
  max-height: 300px;
  background: white; /* 半透明白色背景 */
  border: 1px solid rgba(0, 0, 0, 0.1); /* 淡边框 */
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.infowindow-img {
  width: 100%;
  max-height: 80px;
  object-fit: cover;
  flex-shrink: 0;
  border-right: 1px solid #eee;
}

.infowindow-content {
  padding: 10px;
  flex: 1;
}

.infowindow-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.infowindow-meta {
  font-size: 13px;
  color: #666;
  display: flex;
  gap: 10px;
  margin-bottom: 6px;
}

.infowindow-price {
  color: #fa8919;
  font-size: 14px;
  font-weight: bold;
}
</style>
